package com.alinesno.cloud.notice.transfer;

import java.sql.SQLException;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alinesno.cloud.watcher.core.druid.DruidMonitorStatLogger;
import com.google.common.collect.Lists;

/**
 * 数据库监控配置
 * 
 * @author WeiXiaoJin
 * @since 2022年11月5日 上午6:23:43
 */
@Configuration
public class DruidConfig {

	@Bean(initMethod = "init", destroyMethod = "close")
	@ConfigurationProperties(prefix = "spring.datasource")
	public DruidDataSource dataSource(Filter statFilter) throws SQLException {

		DruidDataSource dataSource = new DruidDataSource();
		
		// 添加自定义的stat，以输出到统一集成平台上面
		DruidMonitorStatLogger logger = new DruidMonitorStatLogger();

		dataSource.setTimeBetweenLogStatsMillis(5*1000);
		dataSource.setFilters("wall,stat");
		dataSource.setUseGlobalDataSourceStat(false);
		dataSource.setStatLogger(logger);
		dataSource.setProxyFilters(Lists.newArrayList(statFilter()));

		return dataSource;
	}

	@Bean
	public Filter statFilter() {
		StatFilter filter = new StatFilter();
		filter.setSlowSqlMillis(90);
		filter.setLogSlowSql(true);
		filter.setMergeSql(true);
		return filter;
	}

}